import json

from django.core.cache import cache
from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from apps.config.models import Role_model, Menu_model
# 角色主页
from apps.config.serializers import Menu_serializer

# roles主页
from apps.config.views.menus_view import Rec_Tree


def roles_view(request):
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'roles/list.html', {'data1': menu_obj.data})


# 角色所有数据
def roles_list(request):
    try:
        roles = Role_model.objects.filter().order_by('role_order')
        count = Role_model.objects.count()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'role全查模块出现问题，请联系管理员！'})
    list1 = []
    for i in roles:
        menu_id = i.role_menu.filter().values_list('id',flat=True)
        menus=list(menu_id)
        dict = {}
        dict['id'] = i.id
        dict['role_code'] = i.role_code
        dict['role_name'] = i.role_name
        dict['role_order'] = i.role_order
        dict['role_byte'] = i.role_byte
        dict['menus_id'] = menus
        dict['now_status'] = i.now_status
        dict['role_per_id'] = i.role_per
        dict['role_per'] = i.get_role_per_display()
        dict['remark_describe'] = i.remark_describe
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        list1.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})


# insert视图
def roles_insert_view(request):
    return render(request, 'roles/insert.html')


# 菜单权限下拉框视图
def roles_menus(request):
    try:
        menu_list = Menu_model.objects.all()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'menus权限下拉框出现问题！请联系管理员'})
    menu_obj = Menu_serializer(menu_list, many=True)
    return JsonResponse({'code': 0, 'data': menu_obj.data})


# role添加动作
@transaction.atomic
def roles_insert(request):
    # 先得判断是否具有添加权限（50500301）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500301' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('role_code')
    name = request.POST.get('role_name')
    order = request.POST.get('role_order')
    byte = request.POST.get('role_byte')
    per = request.POST.get('role_per')
    role = request.POST.get('select')
    now_role = str(role).split(',')
    remark = request.POST.get('remark_describe')
    try:
        menu_obj_list = Menu_model.objects.filter(id__in=now_role)
        role_obj = Role_model.objects.create(role_code=code, role_name=name, role_order=order, role_byte=byte,role_per=per,
                                             remark_describe=remark)
        role_obj.role_menu.add(*menu_obj_list)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查角色代码。'})
        else:
            return JsonResponse({'code': 203, 'msg': '未知错误！请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})


# edit视图
def roles_edit_view(request):
    return render(request, 'roles/edit.html')

# edit动作
@transaction.atomic
def roles_edit(request,id):
    # 先得判断是否具有添加权限（50500302）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500302' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('role_code')
    name = request.POST.get('role_name')
    order = request.POST.get('role_order')
    byte = request.POST.get('role_byte')
    per = request.POST.get('role_per')
    role = request.POST.get('select')
    now_role=str(role).split(',')
    remark = request.POST.get('remark_describe')
    try:
        role_obj = Role_model.objects.get(pk=id)
        menus_objs = Menu_model.objects.filter(id__in=now_role)
        role_obj.role_code=code
        role_obj.role_name=name
        role_obj.role_order=order
        role_obj.role_byte=byte
        role_obj.role_per=per
        role_obj.remark_describe = remark
        role_obj.role_menu.clear()
        role_obj.role_menu.add(*menus_objs)
        role_obj.save()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1406:
            return JsonResponse({'code': 201, 'msg': '数据过长！'})
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查菜单代码。'})
        else:
            return JsonResponse({'code': 203, 'msg': 'menu修改模块出现问题，请联系管理员！'})

    return JsonResponse({'code': 0, 'msg': '修改成功！'})



# 删除动作
@transaction.atomic
def roles_del(request,id):
    # 先得判断是否具有添加权限（50500303）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500303' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        Role_model.objects.get(pk=id).delete()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 202, 'msg': 'menus删除模块出现问题，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '删除成功！'})

# 查询
def roles_search(request):
    name = request.GET.get('searchname')
    try:
        if len(name)==0:
            role_list = Role_model.objects.filter()
        else:
            role_list = Role_model.objects.filter(Q(role_code__contains=name)|Q(role_name__contains=name))
        count = len(list(role_list))
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'role单查模块出现问题，请联系管理员！'})
    list1 = []
    for i in role_list:
        menu_id = i.role_menu.filter().values_list('id', flat=True)
        menus = list(menu_id)
        dict = {}
        dict['id'] = i.id
        dict['role_code'] = i.role_code
        dict['role_name'] = i.role_name
        dict['role_order'] = i.role_order
        dict['role_byte'] = i.role_byte
        dict['menus_id'] = menus
        dict['now_status'] = i.now_status
        dict['role_per_id'] = i.role_per
        dict['role_per'] = i.get_role_per_display()
        dict['remark_describe'] = i.remark_describe
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        list1.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})

# 停启用
def roles_enable(request,id):
    # 先得判断是否具有添加权限（50500304）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500304' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        role_obj = Role_model.objects.get(pk=id)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 202, 'msg': 'role模块禁用动作出现问题！'})
    if role_obj.now_status==0:
        role_obj.now_status=1
        role_obj.save()
        return JsonResponse({'code': 0, 'msg':'禁用成功！'})
    elif role_obj.now_status==1:
        role_obj.now_status = 0
        role_obj.save()
        return JsonResponse({'code': 0, 'msg':'启用成功！'})